package com.example.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.util.Collections;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
        registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/");
        // 配置文件上传目录的访问路径
        registry.addResourceHandler("/uploads/**").addResourceLocations("file:///C:/uploads/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/register").setViewName("register");
        registry.addViewController("/home").setViewName("home");
    }

    @Bean
    public RestTemplate restTemplate() {
        // 创建一个具有超时设置和错误处理的RestTemplate
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30000); // 连接超时时间：30秒
        requestFactory.setReadTimeout(60000); // 读取超时时间：60秒

        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 添加请求拦截器，用于记录请求和响应
        restTemplate.setInterceptors(Collections.singletonList(new LoggingRequestInterceptor()));

        return restTemplate;
    }

    // 内部类：请求日志拦截器
    private static class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
        private static final Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
                throws IOException {
            logger.debug("Request: {} {}", request.getMethod(), request.getURI());
            logger.debug("Request headers: {}", request.getHeaders());

            ClientHttpResponse response = execution.execute(request, body);

            logger.debug("Response status: {}", response.getStatusCode());
            logger.debug("Response headers: {}", response.getHeaders());

            return response;
        }
    }

    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setMaxUploadSize(10485760); // 10MB
        resolver.setMaxUploadSizePerFile(5242880); // 5MB
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }
}